<script src="canvasUtils.js"></script>
<template>
  <view class="share_layout_box">
    <canvas class="myCanvas test" :style="'width:'+myCanvasWidth+'px;height:'+myCanvasHeight+'px'" canvas-id="sharePosterFrendsId"></canvas>
  </view>
</template>
<script>
// let canvasData = { // 图片生成参数
//   userAvatar: 'https://image.qqpyyds.com/user/avatar/1448144136114941954', // 用户头像
//   userNickname: '廖志林',  // 用户昵称
//   ranking: 'NO.6', // 排名
//   viewsOfText: 'scajc ',
//   copyText1: '111',
//   bgImgUrl: 'https://image.qqpyyds.com/uni_app/user/163549354120386.png', // 封面大图片
//   title: '这里是动态标题最多两行这里是动态标题最多两行这里是动态标题最这里是动态多这里是动态题最多两题最多两题最多两', // 标题
//   page: '/pages/index/index', // 二维码地址
// }
// import { writeFile, removeSave } from '@/api/baseConvert'
import share from "@/api/share.js"
import canvasUtils from './canvasUtils'
export default {
  data () {
    return {
      myCanvasWidth: 280,
      myCanvasHeight: 504,
      dpiMun: 3,
    }
  },
  created () {
    this.myCanvasWidth = this.myCanvasWidth*this.dpiMun
    this.myCanvasHeight = this.myCanvasHeight*this.dpiMun
  },
  methods: {
    async sharePosterFrends(data) {
      let _this = this
      let _data = data
      let paramMap = {}
      paramMap = {
        page: _data?.page ?? 'pages/index/index',
        ..._data.options,
        // isHyaline: true,
        // lineColor: {'r':253,'g':253,'b':253},
      }
      share.getSunCode(paramMap).then(async (res_) => {
        if (res_.code == 200) {
          let pam = {
            ..._data,
            QRCode: res_.data,
          }
          await _this.createdCode(pam)
          let shareData = {}
          wx.canvasToTempFilePath({
            canvasId: 'sharePosterFrendsId',
            fileType: 'jpg',
            width: _this.myCanvasWidth,
            height: _this.myCanvasHeight,
            destWidth: _this.myCanvasWidth * 2,
            destHeight: _this.myCanvasHeight * 2,
            success: async (res) => {
              shareData = {
                code: '200',
                msg: '绘制成功！',
                isShareType: data.type,
                url: res.tempFilePath
              }
              console.log(shareData,'绘制成功')
              if (shareData.code == 200) {
                _this.$emit('drawShareCardFn', shareData)
              }
              _this.$store.commit('POSTER_SHARING_DATA', shareData)
              wx.hideLoading()
            },
            fail: function (res) {
              console.log('绘制失败')
            }
          },_this)
          // removeSave() // 先删除在添加
          // writeFile(res_.data).then(async (img)=>{
          // }).catch(e=>{
          //   console.log(e)
          // })
        }
      })
    },
    // 开始绘图
    createdCode (data) {
      const _this = this
      let fromData = data
      return new Promise(resolve => {
        exec()
        async function exec () {
          const ctx = wx.createCanvasContext('sharePosterFrendsId', _this) // 绘图上下文
          let filletRadius = 6*_this.dpiMun
          let gapH = 0
          if (fromData.type == 1) {
            gapH = 63*_this.dpiMun
          }
          ctx.setFillStyle('#E44435')
          ctx.fillRect(0, 0, _this.myCanvasWidth, _this.myCanvasHeight)
          ctx.save()
          _this.handleBorderRect(ctx, 12*_this.dpiMun, 12*_this.dpiMun, 256*_this.dpiMun, 404*_this.dpiMun, filletRadius, '#E44435')
          ctx.clip()
          ctx.setFillStyle('#fff')
          ctx.fillRect(12*_this.dpiMun, 12*_this.dpiMun, 256*_this.dpiMun, 404*_this.dpiMun)
          ctx.save()
          _this.handleBorderRect(ctx, 12*_this.dpiMun, 12*_this.dpiMun, 256*_this.dpiMun, 318*_this.dpiMun-gapH, filletRadius, '#E44435')
          ctx.clip()
          let bgImgUrl = fromData.bgImgUrl
          bgImgUrl = bgImgUrl+`?x-oss-process=image/resize,h_${318*_this.dpiMun-gapH},w_${256*_this.dpiMun},m_fill/auto-orient,1/quality,q_90/format,jpg`
          let bgImgHeight = 280
          if (fromData.type == 0 || fromData.type == 2) {
            bgImgHeight = 342
          }
          await canvasUtils.drawCoverImage(bgImgUrl, ctx, 12*_this.dpiMun, 12*_this.dpiMun, 280*_this.dpiMun, bgImgHeight*_this.dpiMun)
          ctx.restore()
          ctx.save()
          ctx.beginPath()
          ctx.strokeStyle = '#fff'
          ctx.arc(42*_this.dpiMun,337*_this.dpiMun-gapH,20*_this.dpiMun,0,2*Math.PI)
          ctx.fill()
          ctx.clip()
          await _this.drawImg(fromData.userAvatar, ctx, 22*_this.dpiMun, 317*_this.dpiMun-gapH, 40*_this.dpiMun, 40*_this.dpiMun)
          ctx.restore()
          // 视频流显示播放按钮
          if (!fromData.isGoods) {
            await _this.drawImg('https://image.qqpyyds.com/mpAppImg/icon/play3_icon.png', ctx, (256/2-21+12)*_this.dpiMun, (318/2-21+12)*_this.dpiMun-(gapH/2), 42*_this.dpiMun, 42*_this.dpiMun)
          }
          ctx.setFontSize(15*_this.dpiMun)
          ctx.setFillStyle('#323233')
          let userNickname = fromData.userNickname || fromData.communityName
          ctx.fillText(userNickname, 70*_this.dpiMun, 352*_this.dpiMun-gapH, 120*_this.dpiMun)
          if (fromData.viewsOfText) {
            ctx.setFontSize(10*_this.dpiMun)
            ctx.setFillStyle('#323232')
            ctx.fillText(fromData.viewsOfText,  _this.myCanvasWidth-ctx.measureText(fromData.viewsOfText).width-(20*_this.dpiMun), 350*_this.dpiMun-gapH, 80*_this.dpiMun)
          }
          if (fromData.title) {
            let titleStr = fromData.title.length>32?fromData.title.slice(0,31)+'...':fromData.title.slice(0,31)
            ctx.setFontSize(14*_this.dpiMun)
            ctx.setFillStyle('#ffffff')
            ctx.fillText(titleStr, -1000, -1000, 200)
            ctx.setFontSize(14*_this.dpiMun)
            ctx.setFillStyle('#000000')
            _this.wordsWrap(ctx, titleStr, ctx.measureText(titleStr).width, 236*_this.dpiMun, 22*_this.dpiMun, 380*_this.dpiMun-gapH, 20*_this.dpiMun)
          }
          ctx.restore()
          ctx.save()
          ctx.beginPath()
          ctx.setFillStyle('#ffffff')
          // ctx.strokeStyle = '#E44435'
          ctx.arc(_this.myCanvasWidth - (48*_this.dpiMun), _this.myCanvasHeight - (44*_this.dpiMun),36*_this.dpiMun,0,2*Math.PI)
          ctx.fill()
          ctx.clip()
          // await _this.drawImg(fromData.QRCode, ctx, _this.myCanvasWidth-(88*_this.dpiMun), _this.myCanvasHeight-(84*_this.dpiMun), 64*_this.dpiMun, 64*_this.dpiMun)
          await _this.drawImg(fromData.QRCode, ctx, _this.myCanvasWidth - (80*_this.dpiMun), _this.myCanvasHeight - (76*_this.dpiMun), 64*_this.dpiMun, 64*_this.dpiMun)
          ctx.restore()
          ctx.save()
          ctx.setFontSize(12*_this.dpiMun)
          ctx.setFillStyle('#fff')
          ctx.fillText(fromData.copyText1, 24*_this.dpiMun, 454*_this.dpiMun, 150*_this.dpiMun)
          ctx.restore()
          if (fromData.type == 0 || fromData.type == 1) {
            ctx.setFontSize(12*_this.dpiMun)
            ctx.setFillStyle('#fff')
            ctx.fillText(fromData.copyText2, 24*_this.dpiMun, 474*_this.dpiMun, 150*_this.dpiMun)
          }
          if (fromData.type == 2) {
            ctx.setFontSize(18*_this.dpiMun)
            ctx.setFillStyle('#FEDFA6')
            ctx.fillText(fromData.copyText2, 24*_this.dpiMun, 482*_this.dpiMun, 150*_this.dpiMun)
          }
          if (fromData.type == 1) {
            await _this.drawImg('https://image.qqpyyds.com/mpAppImg/other/price_img1.png', ctx, 60*_this.dpiMun, 382*_this.dpiMun, 152*_this.dpiMun, 22*_this.dpiMun)
            ctx.restore()
            ctx.save()
            ctx.setFontSize(12*_this.dpiMun)
            ctx.setFillStyle('#fff')
            ctx.fillText(fromData.price, -1000, -1000, 100*_this.dpiMun)
            let priceL = (_this.myCanvasWidth-ctx.measureText(fromData.price).width)/2
            _this.handleBorderRect(ctx, priceL-(15*_this.dpiMun), 358*_this.dpiMun, ctx.measureText(fromData.price).width+(24*_this.dpiMun), 24*_this.dpiMun, 10*_this.dpiMun, '#E44435')
            ctx.clip()
            ctx.restore()
            ctx.save()
            ctx.setFontSize(12*_this.dpiMun)
            ctx.setFillStyle('#fff')
            ctx.fillText(fromData.price, priceL-(6*_this.dpiMun), 375*_this.dpiMun, 100*_this.dpiMun)
            ctx.restore()
            if (fromData.originalPrice) {
              ctx.setFontSize(10*_this.dpiMun)
              ctx.setFillStyle('#969799')
              ctx.fillText(fromData.originalPrice, 45*_this.dpiMun, 400*_this.dpiMun, 100*_this.dpiMun)
              ctx.restore()
            }
            ctx.setFontSize(10*_this.dpiMun)
            ctx.setFillStyle('#969799')
            ctx.fillText(fromData.copyText3, 186*_this.dpiMun, 400*_this.dpiMun, 100*_this.dpiMun)
          }
          ctx.restore()
          ctx.draw(false, () => {
            resolve()
          })
        }
      })
    },
    // 画4个圆角
    handleBorderRect (ctx, x, y, w, h, r, color) {
      ctx.beginPath()
      // 左上角
      ctx.arc(x + r, y + r, r, Math.PI, 1.5 * Math.PI)
      ctx.moveTo(x + r, y)
      ctx.lineTo(x + w - r, y)
      ctx.lineTo(x + w, y + r)
      // 右上角
      ctx.arc(x + w - r, y + r, r, 1.5 * Math.PI, 2 * Math.PI)
      ctx.lineTo(x + w, y + h - r)
      ctx.lineTo(x + w - r, y + h)
      // 右下角
      ctx.arc(x + w - r, y + h - r, r, 0, 0.5 * Math.PI);
      ctx.lineTo(x + r, y + h)
      ctx.lineTo(x, y + h - r)
      // 左下角
      ctx.arc(x + r, y + h - r, r, 0.5 * Math.PI, Math.PI)
      ctx.lineTo(x, y + r)
      ctx.lineTo(x + r, y)
      ctx.fillStyle = color
      ctx.fill()
      ctx.closePath()
    },
    // 文字自动换行
    wordsWrap (ctx, name, nameWidth, maxWidth, startX, srartY, wordsHight) {
      let lineWidth = 0
      let lastSubStrIndex = 0
      for (let i = 0; i < name.length; i++) {
        lineWidth += ctx.measureText(name[i]).width
        if (lineWidth > maxWidth) {
          ctx.fillText(name.substring(lastSubStrIndex, i), startX, srartY)
          srartY += wordsHight
          lineWidth = 0
          lastSubStrIndex = i
        }
        if (i === name.length - 1) {
          ctx.fillText(name.substring(lastSubStrIndex, i + 1), startX, srartY)
        }
      }
    },
    // 绘制远程网络图片
    async drawImg (url, ctx, startX, startY, width, height) {
      let _this = this
      return new Promise(resolve => {
        exec()
        async function exec () {
          wx.getImageInfo({
            src: url,
            success: function (res) {
              const filePath = res.path
              ctx.drawImage(filePath, startX, startY, width, height)
              resolve()
            },
            fail: function (err) {
              console.log(err)
            },
            complete: function (err) {
              console.log(err)
            }
          })
        }
      })
    }
  }
}
</script>
<style scoped lang="scss">
.share_layout_box {
  position: fixed;
  left: -1000px;
  top: -1000px;
  // z-index: 999;
}
</style>